package jjn.carl.binary_tree;

import commons.BinaryTreeHelper;
import commons.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author Jiang Jining
 * @since 2023-07-12 23:40
 */
public class LeetCode102 {
    public List<List<Integer>> levelOrder(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> level = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                if (poll == null) {
                    continue;
                }
                level.add(poll.val);
                if (poll.left != null) {
                    queue.offer(poll.left);
                }
                if (poll.right != null) {
                    queue.offer(poll.right);
                }
            }
            result.add(level);
        }
        return result;
    }
    
    public static void main(String[] args) {
        List<Integer> input = new ArrayList<>();
        input.addAll(List.of(3, 9, 20));
        input.add(null);
        input.add(null);
        input.add(15);
        input.add(7);
        TreeNode root = BinaryTreeHelper.buildTree(input);
        List<List<Integer>> levelledOrder = new LeetCode102().levelOrder(root);
        System.out.println("levelledOrder = " + levelledOrder);
    }
}
